package logic

import (
	"encoding/json"
	"fmt"
	"github.com/gogap/logs"
	"github.com/shopspring/decimal"
	"log"
	"strconv"
	"sync"
	"time"
	"unicode/utf8"
	"yundian/internel/app/dao"
	"yundian/internel/app/dao/memberdao"
	"yundian/internel/app/helper"
	"yundian/internel/app/helper/request"
	"yundian/internel/app/helper/resphelper/placeresp"
	"yundian/internel/app/models/agentincome"
	"yundian/internel/app/models/cashlog"
	"yundian/internel/app/models/devices"
	"yundian/internel/app/models/dividendslog"
	"yundian/internel/app/models/incomes"
	"yundian/internel/app/models/internalstatistics"
	"yundian/internel/app/models/membermodel"
	"yundian/internel/app/models/orders"
	"yundian/internel/app/models/ordersstatistics"
	"yundian/internel/app/models/placeincome"
	"yundian/internel/app/models/placemodel"
	"yundian/internel/app/models/prices"
	"yundian/internel/app/models/users"
	"yundian/internel/pkg/dingo"
	"yundian/internel/pkg/dingo/global"
	"yundian/internel/pkg/utils"
	"yundian/internel/pkg/wechatpay"
)

type TaskLogic struct {
}

func NewTaskLogic() *TaskLogic {
	return &TaskLogic{}
}

// UpdatePlaceLevel 每天定时更新商户等级
func (task *TaskLogic) UpdatePlaceLevel() {
	// 计算评级
	placeList := dao.NewPlaceDao().GenPlaceUsedRateList().Unwrap().([]placeresp.PlaceUsedRateRankList)

	// 开4个协程 更新商户表
	var wg sync.WaitGroup

	for i := 1; i <= 4; i++ {
		wg.Add(1)
		//if i == 4 {
		//	fmt.Println((i-1)*(len(placeList)/4), len(placeList), placeList[(i-1)*(len(placeList)/4):len(placeList)])
		//} else {
		//	fmt.Println((i-1)*(len(placeList)/4), i*(len(placeList)/4))
		//	//fmt.Println((i-1)*(len(placeList)/4), (i*(len(placeList)/4))-1, placeList[(i-1)*(len(placeList)/4):behind])
		//	fmt.Println((i-1)*(len(placeList)/4), (i*(len(placeList)/4))-1, placeList[(i-1)*(len(placeList)/4):i*(len(placeList)/4)])
		//}

		if i == 4 {
			go func() {
				defer wg.Done()
				task.UpdatePlaceInfo(placeList[(i-1)*(len(placeList)/4) : len(placeList)]) // 更新商户信息
			}()
		} else {
			go func() {
				defer wg.Done()
				task.UpdatePlaceInfo(placeList[(i-1)*(len(placeList)/4) : (i * (len(placeList) / 4))]) // 更新商户信息
			}()
		}
		wg.Wait()
	}

}

func (task *TaskLogic) UpdatePlaceInfo(lists []placeresp.PlaceUsedRateRankList) {
	for _, lst := range lists {
		log := &struct {
			PlaceId   int     `gorm:"column:place_id"`
			PlaceName string  `gorm:"column:place_name"`
			Level     string  `gorm:"column:level"`
			LevelNum  int     `gorm:"column:level_num"`
			UsedRate  float32 `gorm:"column:used_rate"`
			CreateAt  int64   `gorm:"column:create_at"`
			IsSuccess int     `gorm:"column:is_success"`
		}{
			PlaceId:   lst.PlaceId,
			PlaceName: lst.PlaceName,
			Level:     task.Level(lst.UsageRate),
			LevelNum:  task.LevelNum(lst.UsageRate),
			UsedRate:  lst.UsageRate,
			CreateAt:  time.Now().Unix(),
		}
		m := placemodel.NewPlaceModel()
		m.Id = lst.PlaceId
		m.Level = task.Level(lst.UsageRate)
		m.UsedRate = lst.UsageRate
		ok := dao.NewPlaceDao().UpdatePlaceRateById(m).Unwrap().(bool)
		if !ok {
			// 评级失败 - 写入日志
			log.IsSuccess = 2                               // 评级失败
			global.Orm.Table("place_level_log").Create(log) //新增
		} else {
			// 评级成功 - 写入日志
			log.IsSuccess = 1                               // 评级成功
			global.Orm.Table("place_level_log").Create(log) //新增
		}
	}
}

// 测试用
func (task *TaskLogic) UpdatePlaceLevelTest(sday, eday int) {
	// 计算评级
	placeList := dao.NewPlaceDao().GenPlaceUsedRateListTest(sday, eday).Unwrap().([]placeresp.PlaceUsedRateRankList)

	// 开4个协程 更新商户表
	var wg sync.WaitGroup
	for i := 1; i <= 4; i++ {
		wg.Add(1)
		if i == 4 {
			go func(i int) {
				defer wg.Done()
				task.UpdatePlaceInfoTest(placeList[(i-1)*(len(placeList)/4):len(placeList)], eday) // 更新商户信息
			}(i)
		} else {
			go func(i int) {
				defer wg.Done()
				task.UpdatePlaceInfoTest(placeList[(i-1)*(len(placeList)/4):(i*(len(placeList)/4))-1], eday) // 更新商户信息
			}(i)
		}
	}
	wg.Wait()

}

// 测试用
func (task *TaskLogic) UpdatePlaceInfoTest(lists []placeresp.PlaceUsedRateRankList, day int) {
	for _, lst := range lists {
		t := time.Now().AddDate(0, 0, -day)
		log := &struct {
			PlaceId   int     `gorm:"column:place_id"`
			PlaceName string  `gorm:"column:place_name"`
			Level     string  `gorm:"column:level"`
			LevelNum  int     `gorm:"column:level_num"`
			UsedRate  float32 `gorm:"column:used_rate"`
			CreateAt  int64   `gorm:"column:create_at"`
			IsSuccess int     `gorm:"column:is_success"`
		}{
			PlaceId:   lst.PlaceId,
			PlaceName: lst.PlaceName,
			Level:     task.Level(lst.UsageRate),
			LevelNum:  task.LevelNum(lst.UsageRate),
			UsedRate:  lst.UsageRate,
			CreateAt:  t.Unix(),
		}
		m := placemodel.NewPlaceModel()
		m.Id = lst.PlaceId
		m.Level = task.Level(lst.UsageRate)
		m.UsedRate = lst.UsageRate

		log.IsSuccess = 1
		global.Orm.Table("place_level_log").Create(log)

	}
}

// 评级规则 、临时使用，后期更改为后台配置
func (task *TaskLogic) Level(usedRate float32) string {
	if usedRate >= 10.00 {
		return "S"
	} else if usedRate >= 5.00 && usedRate < 10.00 {
		return "A"
	} else if usedRate >= 3.00 && usedRate < 5.00 {
		return "B"
	} else if usedRate >= 1.00 && usedRate < 3.00 {
		return "C"
	} else if usedRate >= 0.10 && usedRate < 1.00 {
		return "D"
	} else if usedRate <= 0.10 {
		return "E"
	}
	return "E"
}

func (task *TaskLogic) LevelNum(usedRate float32) int {
	if usedRate >= 10.00 {
		return 1
	} else if usedRate >= 5.00 && usedRate < 10.00 {
		return 2
	} else if usedRate >= 3.00 && usedRate < 5.00 {
		return 3
	} else if usedRate >= 1.00 && usedRate < 3.00 {
		return 4
	} else if usedRate >= 0.10 && usedRate < 1.00 {
		return 5
	} else if usedRate <= 0.10 {
		return 6
	}
	return 6
}

// ------------------- 定时查看使用时长已到期的用户 -----------------------//

// 微信订单完结任务
func (task *TaskLogic) AutoCompleteMemberOrderByWx(typeName string, prodType uint8) {
	wc := NewSettingLogic().GetPaySettingByTypeName(typeName)
	// 查询订单中正在使用的订单
	var lists []orders.OrderModel
	global.Orm.Table("orders").
		Where("state = ?", 2).
		Where("appid = ?", wc.AppId).
		Where("order_from = ?", "weixin"). // 微信
		Where("prod_type = ?", prodType).Find(&lists)

	maxGoroutine := 4 // 开启协程的大小
	var pool chan struct{}
	pool = make(chan struct{}, maxGoroutine) // 协程池
	var wg sync.WaitGroup
	for _, lst := range lists {
		wg.Add(1)
		pool <- struct{}{}
		go func(lst orders.OrderModel) {
			defer wg.Done()
			defer func() {
				<- pool
			}()
			//log.Println(lst.TradeNo)
			param := &request.CloseOrderReq{}
			param.DeviceSn = lst.DeviceSn
			param.TradeNo = lst.TradeNo
			param.EndTime = time.Now().Unix()
			param.ProductId = lst.ProductId
			param.Openid = lst.Openid

			if lst.Openid == "" {
				m := membermodel.New()
				global.Orm.Table("members").Where("uuid = ?", lst.MemberId).Find(m).Limit(1)
				param.Openid = m.XcxOpenid
			}
			// 判断使用时长是否超时
			useTime := param.EndTime - int64(lst.PayAt)
			ruleInfo := dao.NewPricesDao().GetPriceDetail(lst.ProductId).Unwrap().(*prices.PriceModel)

			if lst.FeeMode == 1 { // 计时
				if useTime/60 >= int64(ruleInfo.MaxTime) {
					NewOrderLogic().HandleWxEndOrder(param)
				}
			} else {
				if useTime/60 >= int64(ruleInfo.UseDuration) {
					NewOrderLogic().HandleWxEndOrder(param)
				}
			}
		}(lst)
	}
}

// 2天前的订单
func (task *TaskLogic) AutoCompleteMemberOrderLastTwoDays() {
	dateStr := time.Now().AddDate(0, 0, -3).Format("2006-01-02")
	// 查询订单中正在使用的订单
	var lists []orders.OrderModel
	global.Orm.Table("orders").
		Where("state = ?", 2).
		Where("DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') < ?", dateStr).Find(&lists)

	maxGoroutine := 4 // 开启协程的大小
	var pool chan struct{}
	pool = make(chan struct{}, maxGoroutine) // 协程池
	var wg sync.WaitGroup
	for _, lst := range lists {
		wg.Add(1)
		pool <- struct{}{}
		go func(lst orders.OrderModel) {
			defer wg.Done()
			defer func() {
				<- pool
			}()
			param := &request.CloseOrderReq{}
			param.DeviceSn = lst.DeviceSn
			param.TradeNo = lst.TradeNo
			param.EndTime = time.Now().Unix()
			param.ProductId = lst.ProductId
			param.Openid = lst.Openid
			if lst.Openid == "" {
				m := membermodel.New()
				global.Orm.Table("members").Where("uuid = ?", lst.MemberId).Find(m).Limit(1)
				param.Openid = m.XcxOpenid
			}

			// 判断使用时长是否超时
			useTime := param.EndTime - int64(lst.PayAt)
			ruleInfo := dao.NewPricesDao().GetPriceDetail(lst.ProductId).Unwrap().(*prices.PriceModel)

			if lst.PayFrom == 2 {
				if lst.FeeMode == 1 { // 计时
					if useTime/60 >= int64(ruleInfo.MaxTime) {
						NewOrderLogic().HandleWxEndOrderDeposit(param)
					}
				} else {
					if useTime/60 >= int64(ruleInfo.UseDuration) {
						NewOrderLogic().HandleWxEndOrderDeposit(param)
					}
				}
			}

			//NewOrderLogic().HandleWxEndOrderDeposit(param)
		}(lst)
	}
}

func (task *TaskLogic) AutoCompleteMemberOrder() {
	wc := NewSettingLogic().GetPaySettingByTypeName("gm")
	// 查询订单中正在使用的订单
	var lists []orders.OrderModel
	global.Orm.Table("orders").
		Where("state = ?", 2).
		Where("appid = ?", wc.AppId).
		Where("order_from = ?", "weixin"). // 微信
		Where("is_draw = 0 and fee_mode = 1").Find(&lists)

	// 遍历正在使用中的订单 - 如果订单的使用时长已超过，则自动扣款
	for _, lst := range lists {
		//log.Println(lst.TradeNo)
		param := &request.CloseOrderReq{}
		param.DeviceSn = lst.DeviceSn
		param.TradeNo = lst.TradeNo
		param.EndTime = time.Now().Unix()
		param.ProductId = lst.ProductId
		param.Openid = lst.Openid

		if lst.Openid == "" {
			m := membermodel.New()
			global.Orm.Table("members").Where("uuid = ?", lst.MemberId).Find(m).Limit(1)
			param.Openid = m.XcxOpenid
		}
		// 判断使用时长是否超时
		useTime := param.EndTime - int64(lst.PayAt)
		ruleInfo := dao.NewPricesDao().GetPriceDetail(lst.ProductId).Unwrap().(*prices.PriceModel)

		if lst.FeeMode == 1 { // 计时
			if useTime/60 >= int64(ruleInfo.MaxTime) {
				NewOrderLogic().HandleWxEndOrder(param)
			}
		} else {
			if useTime/60 >= int64(ruleInfo.UseDuration) {
				NewOrderLogic().HandleWxEndOrder(param)
			}
		}

	}

	// 预授权支付（支付分支付），自动扣款失败则为  待守约
	// 押金支付暂时不需要
}

func (task *TaskLogic) AutoCompleteMemberOrderIsDraw() {
	wc := NewSettingLogic().GetPaySetting()
	// 查询订单中正在使用的订单
	var lists []orders.OrderModel
	global.Orm.Table("orders").
		Where("state = ?", 2).
		Where("appid = ?", wc.AppId).
		Where("order_from = ?", "weixin"). // 微信
		Where("is_draw = 1 and fee_mode = 1").Find(&lists)

	// 遍历正在使用中的订单 - 如果订单的使用时长已超过，则自动扣款
	for _, lst := range lists {
		//log.Println(lst.TradeNo)
		param := &request.CloseOrderReq{}
		param.DeviceSn = lst.DeviceSn
		param.TradeNo = lst.TradeNo
		param.EndTime = time.Now().Unix()
		param.ProductId = lst.ProductId
		param.Openid = lst.Openid

		if lst.Openid == "" {
			m := membermodel.New()
			global.Orm.Table("members").Where("uuid = ?", lst.MemberId).Find(m).Limit(1)
			param.Openid = m.XcxOpenid
		}
		// 判断使用时长是否超时
		useTime := param.EndTime - int64(lst.PayAt)
		ruleInfo := dao.NewPricesDao().GetPriceDetail(lst.ProductId).Unwrap().(*prices.PriceModel)

		if lst.FeeMode == 1 { // 计时
			if useTime/60 >= int64(ruleInfo.MaxTime) {
				NewOrderLogic().HandleWxEndOrder(param)
			}
		} else {
			if useTime/60 >= int64(ruleInfo.UseDuration) {
				NewOrderLogic().HandleWxEndOrder(param)
			}
		}

		// 判断使用时长是否超时
		//useTime := param.EndTime - int64(lst.PayAt)
		//devInfo := dao.NewDeviceDao().FetchDeviceInfoWithType(lst.DeviceSn).Unwrap().(*devices.DeviceType)
		//ruleInfo := dao.NewPricesDao().GetPriceDetail(lst.ProductId).Unwrap().(*prices.PriceModel)
		//
		//if lst.SharedMode == "pcl" && devInfo.DeviceModelId == "XC-PCL-5-002" { // 单套餐
		//	if useTime/60 >= int64(ruleInfo.MaxTime) {
		//		_ = NewOrderLogic().HandleWxEndOrder(param)
		//	}
		//}
		//if lst.SharedMode == "pcl" && devInfo.DeviceModelId == "XC-PCL-5-001" { // 多套餐
		//
		//}
		//if lst.SharedMode == "cdb" { // 充电宝
		//
		//}
		//if lst.SharedMode == "zdsm" { // 自动售货机
		//
		//}
	}

	// 预授权支付（支付分支付），自动扣款失败则为  待守约
	// 押金支付暂时不需要
}

func (task *TaskLogic) AutoCompleteMemberOrderTc() {
	wc := NewSettingLogic().GetPaySetting()
	// 查询订单中正在使用的订单
	var lists []orders.OrderModel
	global.Orm.Table("orders").
		Where("state = ?", 2).
		Where("appid = ?", wc.AppId).
		Where("order_from = ?", "weixin"). // 微信
		Where("is_draw = 0 and fee_mode = 2").Find(&lists)

	// 遍历正在使用中的订单 - 如果订单的使用时长已超过，则自动扣款
	for _, lst := range lists {
		//log.Println(lst.TradeNo)
		param := &request.CloseOrderReq{}
		param.DeviceSn = lst.DeviceSn
		param.TradeNo = lst.TradeNo
		param.EndTime = time.Now().Unix()
		param.ProductId = lst.ProductId
		param.Openid = lst.Openid

		if lst.Openid == "" {
			m := membermodel.New()
			global.Orm.Table("members").Where("uuid = ?", lst.MemberId).Find(m).Limit(1)
			param.Openid = m.XcxOpenid
		}
		// 判断使用时长是否超时
		useTime := param.EndTime - int64(lst.PayAt)
		ruleInfo := dao.NewPricesDao().GetPriceDetail(lst.ProductId).Unwrap().(*prices.PriceModel)

		if lst.FeeMode == 1 { // 计时
			if useTime/60 >= int64(ruleInfo.MaxTime) {
				NewOrderLogic().HandleWxEndOrder(param)
			}
		} else {
			if useTime/60 >= int64(ruleInfo.UseDuration) {
				NewOrderLogic().HandleWxEndOrder(param)
			}
		}

		// 判断使用时长是否超时
		//useTime := param.EndTime - int64(lst.PayAt)
		//devInfo := dao.NewDeviceDao().FetchDeviceInfoWithType(lst.DeviceSn).Unwrap().(*devices.DeviceType)
		//ruleInfo := dao.NewPricesDao().GetPriceDetail(lst.ProductId).Unwrap().(*prices.PriceModel)
		//
		//if lst.SharedMode == "pcl" && devInfo.DeviceModelId == "XC-PCL-5-002" { // 单套餐
		//	if useTime/60 >= int64(ruleInfo.MaxTime) {
		//		_ = NewOrderLogic().HandleWxEndOrder(param)
		//	}
		//}
		//if lst.SharedMode == "pcl" && devInfo.DeviceModelId == "XC-PCL-5-001" { // 多套餐
		//
		//}
		//if lst.SharedMode == "cdb" { // 充电宝
		//
		//}
		//if lst.SharedMode == "zdsm" { // 自动售货机
		//
		//}
	}

	// 预授权支付（支付分支付），自动扣款失败则为  待守约
	// 押金支付暂时不需要
}

func (task *TaskLogic) AutoCompleteMemberOrderIsDrawTc() {
	wc := NewSettingLogic().GetPaySetting()
	// 查询订单中正在使用的订单
	var lists []orders.OrderModel
	global.Orm.Table("orders").
		Where("state = ?", 2).
		Where("appid = ?", wc.AppId).
		Where("order_from = ?", "weixin"). // 微信
		Where("is_draw = 1 and fee_mode = 2").Find(&lists)

	// 遍历正在使用中的订单 - 如果订单的使用时长已超过，则自动扣款
	for _, lst := range lists {
		//log.Println(lst.TradeNo)
		param := &request.CloseOrderReq{}
		param.DeviceSn = lst.DeviceSn
		param.TradeNo = lst.TradeNo
		param.EndTime = time.Now().Unix()
		param.ProductId = lst.ProductId
		param.Openid = lst.Openid

		if lst.Openid == "" {
			m := membermodel.New()
			global.Orm.Table("members").Where("uuid = ?", lst.MemberId).Find(m).Limit(1)
			param.Openid = m.XcxOpenid
		}
		// 判断使用时长是否超时
		useTime := param.EndTime - int64(lst.PayAt)
		ruleInfo := dao.NewPricesDao().GetPriceDetail(lst.ProductId).Unwrap().(*prices.PriceModel)

		if lst.FeeMode == 1 { // 计时
			if useTime/60 >= int64(ruleInfo.MaxTime) {
				NewOrderLogic().HandleWxEndOrder(param)
			}
		} else {
			if useTime/60 >= int64(ruleInfo.UseDuration) {
				NewOrderLogic().HandleWxEndOrder(param)
			}
		}

		// 判断使用时长是否超时
		//useTime := param.EndTime - int64(lst.PayAt)
		//devInfo := dao.NewDeviceDao().FetchDeviceInfoWithType(lst.DeviceSn).Unwrap().(*devices.DeviceType)
		//ruleInfo := dao.NewPricesDao().GetPriceDetail(lst.ProductId).Unwrap().(*prices.PriceModel)
		//
		//if lst.SharedMode == "pcl" && devInfo.DeviceModelId == "XC-PCL-5-002" { // 单套餐
		//	if useTime/60 >= int64(ruleInfo.MaxTime) {
		//		_ = NewOrderLogic().HandleWxEndOrder(param)
		//	}
		//}
		//if lst.SharedMode == "pcl" && devInfo.DeviceModelId == "XC-PCL-5-001" { // 多套餐
		//
		//}
		//if lst.SharedMode == "cdb" { // 充电宝
		//
		//}
		//if lst.SharedMode == "zdsm" { // 自动售货机
		//
		//}
	}

	// 预授权支付（支付分支付），自动扣款失败则为  待守约
	// 押金支付暂时不需要
}

// 国曼科技小程序 - 密码线充 - 微信 - T-1前的订单
func (task *TaskLogic) AutoCompleteGmOrders() {
	wc := NewSettingLogic().GetPaySettingByTypeName("gm")
	dateStr := time.Now().AddDate(0, 0, -2).Format("2006-01-02")
	// 查询订单中正在使用的订单
	var lists []orders.OrderModel
	global.Orm.Table("orders").
		Where("state = ?", 2).
		Where("appid = ?", wc.AppId).
		Where("order_from = ?", "weixin").
		Where("DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') <= ?", dateStr).
		Find(&lists)

	maxGoroutine := 4 // 开启协程的大小
	var pool chan struct{}
	pool = make(chan struct{}, maxGoroutine) // 协程池
	var wg sync.WaitGroup
	for _, lst := range lists {
		wg.Add(1)
		pool <- struct{}{}
		go func(item orders.OrderModel) {
			defer wg.Done()
			defer func() {
				<- pool
			}()
			//log.Println(lst.TradeNo)
			param := &request.CloseOrderReq{}
			param.DeviceSn = item.DeviceSn
			param.TradeNo = item.TradeNo
			param.EndTime = time.Now().Unix()
			param.ProductId = item.ProductId
			param.Openid = item.Openid

			NewOrderLogic().HandleWxEndOrder(param)
		}(lst)
	}
}

// 中曼速充小程序 - 客房管家 - 微信 - T-1前的订单
func (task *TaskLogic) AutoCompleteZmOrders() {
	wc := NewSettingLogic().GetPaySettingByTypeName("zm")
	dateStr := time.Now().AddDate(0, 0, -2).Format("2006-01-02")
	// 查询订单中正在使用的订单
	var lists []orders.OrderModel
	global.Orm.Table("orders").
		Where("state = ?", 2).
		Where("appid = ?", wc.AppId).
		Where("order_from = ?", "weixin").
		Where("DATE_FORMAT(FROM_UNIXTIME(create_at),'%Y-%m-%d') <= ?", dateStr).
		Find(&lists)

	maxGoroutine := 4 // 开启协程的大小
	var pool chan struct{}
	pool = make(chan struct{}, maxGoroutine) // 协程池
	var wg sync.WaitGroup
	for _, lst := range lists {
		wg.Add(1)
		pool <- struct{}{}
		go func(item orders.OrderModel) {
			defer wg.Done()
			defer func() {
				<- pool
			}()
			//log.Println(lst.TradeNo)
			param := &request.CloseOrderReq{}
			param.DeviceSn = item.DeviceSn
			param.TradeNo = item.TradeNo
			param.EndTime = time.Now().Unix()
			param.ProductId = item.ProductId
			param.Openid = item.Openid

			NewOrderLogic().HandleWxEndOrder(param)
		}(lst)
	}
}

// ------------------- 定时更新 商户每天的收益 ----------------------------//
func (task *TaskLogic) TaskUpdatePlaceIncome() {
	placeList := dao.NewPlaceDao().GenPlaceUsedRateList().Unwrap().([]placeresp.PlaceUsedRateRankList)

	// 开4个协程 更新商户表
	var wg sync.WaitGroup
	if len(placeList) >= 20 {
		for i := 1; i <= 4; i++ {
			wg.Add(1)
			if i == 4 {
				go func(i int) {
					defer wg.Done()
					task.UpdatePlaceIncomeByDay(placeList[(i-1)*(len(placeList)/4) : len(placeList)]) // 更新商户信息
				}(i)
			} else {
				go func(i int) {
					defer wg.Done()
					task.UpdatePlaceIncomeByDay(placeList[(i-1)*(len(placeList)/4) : (i * (len(placeList) / 4))]) // 更新商户信息
				}(i)
			}
			wg.Wait()
		}
	}

	if len(placeList) <= 20 {
		wg.Add(1)
		go func() {
			defer wg.Done()
			task.UpdatePlaceIncomeByDay(placeList[0:len(placeList)]) // 更新商户信息
		}()
		wg.Wait()
	}

}

// 获取商户昨日的收益
func (task *TaskLogic) UpdatePlaceIncomeByTomorrow(lists []placeresp.PlaceUsedRateRankList) {
	for _, lst := range lists {
		// 获取商户的user_id
		userInfo := dao.NewUserDao().GetUserInfoByPlaceId(lst.PlaceId).Unwrap().(*users.UserModel)
		log.Println(userInfo.Name)
	}
}

// 获取商户每天的收益
func (task *TaskLogic) UpdatePlaceIncomeByDay(lists []placeresp.PlaceUsedRateRankList) {
	for _, lst := range lists {
		// 获取商户的user_id
		userInfo := dao.NewUserDao().GetUserInfoByPlaceId(lst.PlaceId).Unwrap().(*users.UserModel)
		dList := dao.NewOrderDao().GetDividendsListByUserId(userInfo.ID).Unwrap().([]dividendslog.PlaceProfitInfoByDay)
		for _, dl := range dList {
			log.Println(dl.Total, dl.Day, dl.Id, dl.UserName)
			m := incomes.New()
			m.DateStr = dl.Day
			m.Type = 1
			m.CreateAt = dingo.Time(time.Now().Unix())
			m.Income = dl.Total
			m.UserId = userInfo.ID

			// 判断当前日期是否存在，存在更新，不存在新增
			var count int64
			global.Orm.Table("incomes").Where("date_str = ?", dl.Day).Count(&count)
			if count > 0 {
				global.Orm.Table("incomes").Where("date_str = ?", dl.Day).Model(&m).Updates(m)
			} else { // 新增
				global.Orm.Table("incomes").Create(m)
			}
		}
	}
}

// 定时任务更新 orders_statistics 表
func (task *TaskLogic) UpdateOrderStatistics(currDate string) {
	// 获取统计值，定时器凌晨1点运行，统计昨天一整天收效
	createAt := time.Now().AddDate(0, 0, -1).Unix()
	if currDate == "" {
		currDate = time.Now().AddDate(0, 0, -1).Format("20060102")
	} else if len(currDate) > 8 {
		createAt = wechatpay.ConvIntTime(currDate)
		// 截取字段串： string:20210407010203 -> string:20210407
		currDate = currDate[0:8]
	}

	//stamp, _ := time.ParseInLocation("20060102", currDate, time.FixedZone("Asia/Shanghai", 8*60*60))
	log.Println("统计时间 ：", currDate)
	data := dao.NewOrderDao().GetOrdersStatistics(currDate)
	lists := data.Unwrap().([]*ordersstatistics.OrdersstatisticsModel)

	for _, lst := range lists {
		placeInfo := dao.NewPlaceDao().GetPlaceById(lst.PlaceId).Unwrap().(*placemodel.PlaceModel)
		lst.PlaceName = placeInfo.PlaceName    //商户名称
		lst.PlaceCreateAt = placeInfo.CreateAt // 商户创建时间
		lst.CreateAt = dingo.Time(createAt)
		//lst.CreateAt = dingo.Time(time.Now().AddDate(0, 0, -1).Unix()) //创建时间为前一天
		// 商户当天收益
		lst.Income = dao.NewOrderDao().GetPlaceIncomeCount(placeInfo.UserID, currDate, lst.SharedMode).Unwrap().(int64)

		// 获取代理商ID
		userInfo := dao.NewUserDao().GetUserInfoByPlaceId(placeInfo.Id).Unwrap().(*users.UserModel)
		uInfo := dao.GetParentUserInfoById(userInfo)
		lst.AgentUserId = uInfo.ID

		// 通过网点和时间查询，
		info := dao.NewOrderDao().GetOrdersStatisticsByPlaceIdTime(lst, currDate).Unwrap().(*ordersstatistics.OrdersstatisticsModel)

		if info.ID > 0 {
			// 如果数据存在，进行更新，
			//log.Println("更新方法--------: ",index)
			dao.NewOrderDao().UpdateOrdersStatistics(lst)
		} else {
			// 如果数据不存在，进行新增，
			//log.Println("新增方法--------: ",index)
			dao.NewOrderDao().InsertOrdersStatistics(lst)
		}
	}
}

// 定时任务更新 代理商每日收益
func (task *TaskLogic) AgentIncomeStatistics(days int, sharedMode string) {
	agentList := dao.NewUserDao().GetAgentUserLists().Unwrap().([]users.AgentInfo)
	if len(agentList) <= 4 {
		task.UpdateAgentIncomeStatistics(agentList, days, sharedMode)
	} else {
		// 开4个协程
		var wg sync.WaitGroup
		for i := 1; i <= 4; i++ {
			wg.Add(1)
			if i == 4 {
				go func(i int) {
					defer wg.Done()
					task.UpdateAgentIncomeStatistics(agentList[(i-1)*(len(agentList)/4):len(agentList)], days, sharedMode) // 更新商户信息
				}(i)
			} else {
				go func(i int) {
					defer wg.Done()
					task.UpdateAgentIncomeStatistics(agentList[(i-1)*(len(agentList)/4):i*(len(agentList)/4)], days, sharedMode) // 更新商户信息
				}(i)
			}
			wg.Wait()
		}
	}
}

func (task *TaskLogic) AgentIncomeStatisticsByDay(days string, sharedMode string) {
	// 1、获取所有代理商用户

	//agentList := dao.NewUserDao().GetAgentUserListsTest([]int{510, 300003, 300006, 300009, 300010, 300028, 300029, 300034, 300041, 300067, 300076, 300111, 300122, 300143, 300190, 300191, 300202, 300212, 300242, 300302}).Unwrap().([]users.AgentInfo)
	//
	//task.UpdateAgentIncomeStatistics(agentList, days, sharedMode) // 更新商户信息

	//log.Println(agentList)
	agentList := dao.NewUserDao().GetAgentUserLists().Unwrap().([]users.AgentInfo)
	if len(agentList) <= 4 {
		task.UpdateAgentIncomeStatisticsByDay(agentList, days, sharedMode)
	} else {
		// 开4个协程
		var wg sync.WaitGroup
		for i := 1; i <= 4; i++ {
			wg.Add(1)
			if i == 4 {
				go func(i int) {
					defer wg.Done()
					task.UpdateAgentIncomeStatisticsByDay(agentList[(i-1)*(len(agentList)/4):len(agentList)], days, sharedMode) // 更新商户信息
				}(i)
			} else {
				go func(i int) {
					defer wg.Done()
					task.UpdateAgentIncomeStatisticsByDay(agentList[(i-1)*(len(agentList)/4):i*(len(agentList)/4)], days, sharedMode) // 更新商户信息
				}(i)
			}
			wg.Wait()
		}

	}
}

func (task *TaskLogic) UpdateAgentIncomeStatistics(lists []users.AgentInfo, days int, sharedMode string) {
	log.Println(lists)
	for _, lst := range lists {
		if days > 0 {
			for d := 1; d <= days; d++ {
				dateStr := time.Now().AddDate(0, 0, -d).Format("2006-01-02")
				m := agentincome.NewAgentIncomeModel()
				m.AgentUserId = lst.ID
				m.AgentUserName = lst.UserName
				m.Phone = lst.Phone
				m.UserNo = lst.UserNo
				m.SharedMode = sharedMode
				m.TradeTotal = dao.NewAgentCountDao().GetAgentTotalMoney(lst.ID, d, sharedMode).Unwrap().(int64) // 交易 总额
				//m.DrawMoney = dao.NewAgentCountDao().GetAgentTotalMoneyByDraw(lst.ID, d, sharedMode).Unwrap().(int64) // 抽单收益
				//m.DrawCount = dao.NewAgentCountDao().GetAgentTotalDrawCount(lst.ID, d, sharedMode).Unwrap().(int64)   //抽单总金额
				m.DivindsMoney = dao.NewAgentCountDao().GetAgentIncomeNoDraw(lst.ID, d, sharedMode).Unwrap().(int64) // 分红收益
				//m.TotalMoney = decimal.NewFromInt(m.DrawMoney).Add(decimal.NewFromInt(m.DivindsMoney)).IntPart()
				m.TotalMoney = m.DivindsMoney
				m.OrderCount = dao.NewAgentCountDao().GetAgentTotalOrderByCreate(lst.ID, d, sharedMode).Unwrap().(int64)    // 生成的订单数
				m.CompleteCount = dao.NewAgentCountDao().GetAgentTotalOrderCount(lst.ID, d, 5, sharedMode).Unwrap().(int64) // 已完成订单数
				m.CancelCount = dao.NewAgentCountDao().GetAgentTotalOrderCount(lst.ID, d, 3, sharedMode).Unwrap().(int64)   // 已撤销订单数
				m.PlacesTotal = dao.NewAgentCountDao().GetPlacesTotal(lst.ID).Unwrap().(int64)                              //获取网点总数
				m.DeviceTotal = dao.NewAgentCountDao().GetDeviceTotal(lst.ID).Unwrap().(int64)                              //获取设备总数
				m.Name = lst.Name
				m.IncomeDay = dateStr

				count := dao.NewAgentCountDao().CountAgentIncomeInfo(lst.ID, dateStr, sharedMode).Unwrap().(int64)
				if count > 0 { // 更新
					dao.NewAgentCountDao().UpdateAgentIncomeInfo(m)
				} else { // 新增
					dao.NewAgentCountDao().InsertAgentIncomeInfo(m)
				}
			}
		}
	}
}

func (task *TaskLogic) UpdateAgentIncomeStatisticsByDay(lists []users.AgentInfo, dateStr, sharedMode string) {
	//log.Println(lists)
	for _, lst := range lists {
		m := agentincome.NewAgentIncomeModel()
		m.AgentUserId = lst.ID
		m.AgentUserName = lst.UserName
		m.Phone = lst.Phone
		m.UserNo = lst.UserNo
		m.SharedMode = sharedMode
		m.TradeTotal = dao.NewAgentCountDao().GetAgentTotalMoneyByDate(lst.ID, sharedMode, dateStr).Unwrap().(int64) // 交易 总额
		//m.DrawMoney = dao.NewAgentCountDao().GetAgentTotalMoneyByDraw(lst.ID, d, sharedMode).Unwrap().(int64) // 抽单收益
		//m.DrawCount = dao.NewAgentCountDao().GetAgentTotalDrawCount(lst.ID, d, sharedMode).Unwrap().(int64)   //抽单总金额
		m.DivindsMoney = dao.NewAgentCountDao().GetAgentIncomeNoDrawByDate(lst.ID, sharedMode, dateStr).Unwrap().(int64) // 分红收益
		//m.TotalMoney = decimal.NewFromInt(m.DrawMoney).Add(decimal.NewFromInt(m.DivindsMoney)).IntPart()
		m.TotalMoney = m.DivindsMoney
		m.OrderCount = dao.NewAgentCountDao().GetAgentTotalOrderByCreateByDate(lst.ID, sharedMode, dateStr).Unwrap().(int64)    // 生成的订单数
		m.CompleteCount = dao.NewAgentCountDao().GetAgentTotalOrderCountByDate(lst.ID, 5, sharedMode, dateStr).Unwrap().(int64) // 已完成订单数
		m.CancelCount = dao.NewAgentCountDao().GetAgentTotalOrderCountByDate(lst.ID, 3, sharedMode, dateStr).Unwrap().(int64)   // 已撤销订单数
		m.PlacesTotal = dao.NewAgentCountDao().GetPlacesTotal(lst.ID).Unwrap().(int64)                                          //获取网点总数
		m.DeviceTotal = dao.NewAgentCountDao().GetDeviceTotal(lst.ID).Unwrap().(int64)                                          //获取设备总数
		m.Name = lst.Name
		m.IncomeDay = dateStr

		count := dao.NewAgentCountDao().CountAgentIncomeInfo(lst.ID, dateStr, sharedMode).Unwrap().(int64)
		if count > 0 { // 更新
			dao.NewAgentCountDao().UpdateAgentIncomeInfo(m)
		} else { // 新增
			//dao.NewAgentCountDao().InsertAgentIncomeInfo(m)
		}
	}
}

// 定时任务更新 分公司每日收益 - dingo
func (task *TaskLogic) BranchIncomeStatistics(days int, sharedMode string) {
	// 1、获取所有代理商用户
	agentList := dao.NewUserDao().GetBranchUserLists().Unwrap().([]users.AgentInfo)
	//log.Println(agentList)
	if len(agentList) <= 4 {
		task.UpdateBranchIncomeStatistics(agentList, days, sharedMode)
	} else {
		// 开4个协程
		var wg sync.WaitGroup
		for i := 1; i <= 4; i++ {
			wg.Add(1)
			if i == 4 {
				go func(i int) {
					defer wg.Done()
					task.UpdateBranchIncomeStatistics(agentList[(i-1)*(len(agentList)/4):len(agentList)], days, sharedMode) // 更新商户信息
				}(i)
			} else {
				go func(i int) {
					defer wg.Done()
					task.UpdateBranchIncomeStatistics(agentList[(i-1)*(len(agentList)/4):i*(len(agentList)/4)], days, sharedMode) // 更新商户信息
				}(i)
			}
			wg.Wait()
		}

	}
}

func (task *TaskLogic) UpdateBranchIncomeStatistics(lists []users.AgentInfo, days int, sharedMode string) {
	for _, lst := range lists {
		if days > 0 {
			for d := 1; d <= days; d++ {
				//查询该用户下的所有网点
				//placesIdArr := dao.NewUserDao().GetPlacesId(lst.ID).Unwrap().([]int)
				dateStr := time.Now().AddDate(0, 0, -d).Format("2006-01-02")
				m := agentincome.NewBranchIncomeModel()
				m.BranchUserId = lst.ID
				m.BranchUserName = lst.UserName
				m.Phone = lst.Phone
				m.UserNo = lst.UserNo
				m.SharedMode = sharedMode
				m.TradeTotal = dao.NewAgentCountDao().GetBranchTotalMoney(lst.ID, d, sharedMode).Unwrap().(int64) // 交易 总额
				//m.DrawMoney = dao.NewAgentCountDao().GetAgentTotalMoneyByDraw(lst.ID, d, sharedMode).Unwrap().(int64) // 抽单收益
				//m.DrawMoney = dao.NewAgentCountDao().GetBranchTotalMoneyByDraw(placesIdArr, d, sharedMode).Unwrap().(int64) // 抽单收益
				//m.DrawCount = dao.NewAgentCountDao().GetAgentTotalDrawCount(lst.ID, d, sharedMode).Unwrap().(int64) //抽单总金额
				m.DivindsMoney = dao.NewAgentCountDao().GetAgentIncomeNoDraw(lst.ID, d, sharedMode).Unwrap().(int64) // 分红收益

				m.TotalMoney = m.DivindsMoney
				//m.TotalMoney = decimal.NewFromInt(m.DrawMoney).Add(decimal.NewFromInt(m.DivindsMoney)).IntPart()
				m.OrderCount = dao.NewAgentCountDao().GetBranchTotalOrderByCreate(lst.ID, d, sharedMode).Unwrap().(int64)    // 生成的订单数
				m.CompleteCount = dao.NewAgentCountDao().GetBranchTotalOrderCount(lst.ID, d, 5, sharedMode).Unwrap().(int64) // 已完成订单数
				m.CancelCount = dao.NewAgentCountDao().GetBranchTotalOrderCount(lst.ID, d, 3, sharedMode).Unwrap().(int64)   // 已撤销订单数
				m.PlacesTotal = dao.NewAgentCountDao().GetBranchPlacesTotal(lst.ID).Unwrap().(int64)                         //获取网点总数
				m.DeviceTotal = dao.NewAgentCountDao().GetBranchDeviceTotal(lst.ID).Unwrap().(int64)                         //获取设备总数
				m.Name = lst.Name
				m.IncomeDay = dateStr

				count := dao.NewAgentCountDao().CountBranchIncomeInfo(lst.ID, dateStr, sharedMode).Unwrap().(int64)
				if count > 0 { // 更新
					dao.NewAgentCountDao().UpdateBranchIncomeInfo(m)
				} else { // 新增
					dao.NewAgentCountDao().InsertBranchIncomeInfo(m)
				}
			}

		}
	}
}

//-----------网点
func (task *TaskLogic) PlaceIncomeStatistics(days int, sharedMode string) {

	// 1、获取所有代理商用户
	placeList := dao.NewPlaceDao().GetPlaceArr().Unwrap().([]placemodel.PlaceModel)

	//log.Println(agentList)
	if len(placeList) <= 4 {
		task.UpdatePlaceIncomeStatistics(placeList, days, sharedMode)
	} else {
		// 开4个协程
		var wg sync.WaitGroup
		for i := 1; i <= 4; i++ {
			wg.Add(1)
			if i == 4 {
				go func(i int) {
					defer wg.Done()
					task.UpdatePlaceIncomeStatistics(placeList[(i-1)*(len(placeList)/4):len(placeList)], days, sharedMode) // 更新商户信息
				}(i)
			} else {
				go func(i int) {
					defer wg.Done()
					task.UpdatePlaceIncomeStatistics(placeList[(i-1)*(len(placeList)/4):i*(len(placeList)/4)], days, sharedMode) // 更新商户信息
				}(i)
			}
			wg.Wait()
		}

	}
}

func (task *TaskLogic) UpdatePlaceIncomeStatistics(lists []placemodel.PlaceModel, days int, sharedMode string) {
	for _, lst := range lists {
		if days > 0 {
			for d := 1; d <= days; d++ {
				//查询该用户下的所有网点
				//placesIdArr := dao.NewUserDao().GetPlacesId(lst.ID).Unwrap().([]int)
				dateStr := time.Now().AddDate(0, 0, -d).Format("2006-01-02")
				//d := time.Now().AddDate(0, 0, -d).Unix()
				m := &placeincome.PlaceIncomeModel{}
				m.PlaceId = lst.Id             //网点ID
				m.PlaceName = lst.PlaceName    //网点名称
				m.PlaceCreateAt = lst.CreateAt //创建时间
				m.IncomeDay = dateStr          //天数
				m.SharedMode = sharedMode
				m.AgentUserId = lst.UserID
				m.SettlementMoney = dao.NewAgentCountDao().GetPlaceTotalMoneyByDraw(lst.Id, d, sharedMode).Unwrap().(int64) // 交易 总额

				m.Income = dao.NewAgentCountDao().GetAPlaceIncomeNoDraw(lst.Id, lst.UserID, d, sharedMode).Unwrap().(int64) // 分红收益

				m.OrderCount = dao.NewAgentCountDao().GetPlaceTotalOrderByCreate(lst.Id, d, sharedMode).Unwrap().(int64)    // 生成的订单数
				m.CompleteCount = dao.NewAgentCountDao().GetPlaceTotalOrderCount(lst.Id, d, 5, sharedMode).Unwrap().(int64) // 已完成订单数
				m.CancelCount = dao.NewAgentCountDao().GetPlaceTotalOrderCount(lst.Id, d, 3, sharedMode).Unwrap().(int64)   // 已撤销订单数
				m.DeviceTotal = dao.NewAgentCountDao().GetPlaceDeviceTotal(lst.Id).Unwrap().(int64)                         //获取设备总数
				m.HotelId = lst.HotelId
				count := dao.NewAgentCountDao().CountPlaceIncomeInfo(lst.Id, dateStr, sharedMode).Unwrap().(int64)
				if count > 0 { // 更新
					dao.NewAgentCountDao().UpdatePlaceIncomeInfo(m)
				} else { // 新增
					//dao.NewAgentCountDao().InsertPlaceIncomeInfo(m)
				}
			}
		}
	}
}

func (task *TaskLogic) UpdatePlaceIncomeTest(days int, sharedMode string) {
	//dateStr := time.Now().AddDate(0, 0, -d).Format("2006-01-02")
	dateStr := "2021-06-11"
	userIdArr := dao.NewUserDao().GetUserIds().Unwrap().([]int)
	placeIdArr := dao.NewPlaceDao().GetPlaceIds().Unwrap().([]int)
	// 1、获取所有代理商用户
	task.SeparateUpdatePlaceIncomeStatistics(dateStr, sharedMode, userIdArr, placeIdArr)

}

func (task *TaskLogic) UpdatePlaceIncomeStatisticsAll(days int, sharedMode string) {
	if days > 0 {
		for d := 1; d <= days; d++ {
			//查询该用户下的所有网点
			//placesIdArr := dao.NewUserDao().GetPlacesId(lst.ID).Unwrap().([]int)
			dateStr := time.Now().AddDate(0, 0, -d).Format("2006-01-02")
			userIdArr := dao.NewUserDao().GetUserIds().Unwrap().([]int)
			placeIdArr := dao.NewPlaceDao().GetPlaceIds().Unwrap().([]int)
			// 1、获取所有代理商用户

			task.SeparateUpdatePlaceIncomeStatistics(dateStr, sharedMode, userIdArr, placeIdArr)
		}
	}

}

// ------------------ 计算商户入场费是否达标 ----------------------------//
func (task *TaskLogic) UpdatePlaceEntry() {
	// 获取进场中的商户列表
	placeList := dao.NewPlaceDao().GetPlaceListByEntryStatus(1).Unwrap().([]placeresp.PlaceToEntry)

	if len(placeList) <= 4 {
		task.UpdatePlaceEntryStatus(placeList)
	} else {
		// 开4个协程 更新商户表
		var wg sync.WaitGroup
		for i := 1; i <= 4; i++ {
			wg.Add(1)
			if i == 4 {
				go func(i int) {
					defer wg.Done()
					task.UpdatePlaceEntryStatus(placeList[(i-1)*(len(placeList)/4) : len(placeList)]) // 更新商户信息
				}(i)
			} else {
				go func(i int) {
					defer wg.Done()
					task.UpdatePlaceEntryStatus(placeList[(i-1)*(len(placeList)/4) : (i * (len(placeList) / 4))]) // 更新商户信息
				}(i)
			}
			wg.Wait()
		}

	}

}

// 更新进场状态
func (task *TaskLogic) UpdatePlaceEntryStatus(lists []placeresp.PlaceToEntry) {
	for _, lst := range lists {
		// 判断商户是否达标,达标则修改状态
		if lst.EntryMoney > 0 && lst.EntryAt > 0 {
			total := dao.NewOrderDao().GetUserIncomeBeginTime(lst.Id, int64(lst.EntryAt)).Unwrap().(int64)

			if total >= lst.EntryMoney*100 {
				log.Printf("商户: %s--已达标,金额为: %d \n", lst.PlaceName, total)
				m := placemodel.NewPlaceModel()
				m.Id = lst.Id
				m.EntryStatus = 2 // 1进行中  2已达标
				m.Status = 4      // 预警商户-进场模式预警
				dao.NewPlaceDao().UpdatePlaceEntryStatusById(m).Unwrap()
			} else {
				log.Printf("商户: %s--未达标,金额为: %d \n", lst.PlaceName, total)
			}
		}

	}
}

func (task *TaskLogic) SeparateAgentIncomeStatistics(days string, sharedMode string) {

	// 1、获取所有代理商用户
	agentList := dao.NewUserDao().GetAgentUserLists().Unwrap().([]users.AgentInfo)
	if len(agentList) <= 4 {
		task.SeparateUpdateAgentIncomeStatistics(agentList, days, sharedMode)
	} else {
		// 开4个协程
		var wg sync.WaitGroup
		for i := 1; i <= 4; i++ {
			wg.Add(1)
			if i == 4 {
				go func(i int) {
					defer wg.Done()
					task.SeparateUpdateAgentIncomeStatistics(agentList[(i-1)*(len(agentList)/4):len(agentList)], days, sharedMode) // 更新商户信息
				}(i)
			} else {
				go func(i int) {
					defer wg.Done()
					task.SeparateUpdateAgentIncomeStatistics(agentList[(i-1)*(len(agentList)/4):i*(len(agentList)/4)], days, sharedMode) // 更新商户信息
				}(i)
			}

		}
		wg.Wait()
	}
}

//-----------代理商
func (task *TaskLogic) SeparateUpdateAgentIncomeStatistics(lists []users.AgentInfo, date string, sharedMode string) {
	//userIds := dao.NewUserDao().GetUserIds().Unwrap().([]int)

	//查询网点分红收益
	//placeDividendsMap := make(map[string]int64)
	//placeDividendsList := dao.NewPlaceDao().GetAgentDividendsByDate(userIds, date, sharedMode).Unwrap().([]users.AgentDividendsModel)
	//
	//for _, v := range placeDividendsList {
	//	placeDividendsMap[strconv.Itoa(v.UserId)] = v.UserMoney
	//}

	for _, lst := range lists {
		dateStr := date
		m := agentincome.NewAgentIncomeModel()
		m.AgentUserId = lst.ID
		m.AgentUserName = lst.UserName
		m.Phone = lst.Phone
		m.UserNo = lst.UserNo
		m.SharedMode = sharedMode
		m.TradeTotal = dao.NewAgentCountDao().GetSeparateAgentTotalMoney(lst.ID, date, sharedMode).Unwrap().(int64) // 交易 总额
		//m.DrawMoney = dao.NewAgentCountDao().GetAgentTotalMoneyByDraw(lst.ID, d, sharedMode).Unwrap().(int64) // 抽单收益
		//m.DrawCount = dao.NewAgentCountDao().GetAgentTotalDrawCount(lst.ID, d, sharedMode).Unwrap().(int64)   //抽单总金额
		m.DivindsMoney = dao.NewAgentCountDao().GetSeparateAgentIncomeNoDraw(lst.ID, date, sharedMode).Unwrap().(int64) // 分红收益
		//m.TotalMoney = decimal.NewFromInt(m.DrawMoney).Add(decimal.NewFromInt(m.DivindsMoney)).IntPart()
		m.TotalMoney = m.DivindsMoney
		m.OrderCount = dao.NewAgentCountDao().GetSeparateAgentTotalOrderByCreate(lst.ID, date, sharedMode).Unwrap().(int64)    // 生成的订单数
		m.CompleteCount = dao.NewAgentCountDao().GetSeparateAgentTotalOrderCount(lst.ID, 5, date, sharedMode).Unwrap().(int64) // 已完成订单数
		m.CancelCount = dao.NewAgentCountDao().GetSeparateAgentTotalOrderCount(lst.ID, 3, date, sharedMode).Unwrap().(int64)   // 已撤销订单数
		m.PlacesTotal = dao.NewAgentCountDao().GetPlacesTotal(lst.ID).Unwrap().(int64)                                         //获取网点总数
		m.DeviceTotal = dao.NewAgentCountDao().GetDeviceTotal(lst.ID).Unwrap().(int64)                                         //获取设备总数
		m.Name = lst.Name
		m.IncomeDay = dateStr

		count := dao.NewAgentCountDao().CountAgentIncomeInfo(lst.ID, dateStr, sharedMode).Unwrap().(int64)
		if count > 0 { // 更新
			dao.NewAgentCountDao().UpdateAgentIncomeInfo(m)
		} else { // 新增
			dao.NewAgentCountDao().InsertAgentIncomeInfo(m)
		}
	}

}

//单独代理执行统计
func (task *TaskLogic) SingleAgentIncomeStatistics(userId int, days []string, dayInt int, sharedMode string) {
	agentInfo := dao.NewUserDao().GetOperatingUser(userId).Unwrap().(users.AgentInfo)
	if len(days) > 0 {
		for _, date := range days {
			//date := time.Now().AddDate(0, 0, -d).Format("2006-01-02")

			m := agentincome.NewAgentIncomeModel()
			m.AgentUserId = agentInfo.ID
			m.AgentUserName = agentInfo.UserName
			m.Phone = agentInfo.Phone
			m.UserNo = agentInfo.UserNo
			m.SharedMode = sharedMode
			m.TradeTotal = dao.NewAgentCountDao().GetSeparateAgentTotalMoney(agentInfo.ID, date, sharedMode).Unwrap().(int64) // 交易 总额
			//m.DrawMoney = dao.NewAgentCountDao().GetAgentTotalMoneyByDraw(lst.ID, d, sharedMode).Unwrap().(int64) // 抽单收益
			//m.DrawCount = dao.NewAgentCountDao().GetAgentTotalDrawCount(lst.ID, d, sharedMode).Unwrap().(int64)   //抽单总金额
			m.DivindsMoney = dao.NewAgentCountDao().GetSeparateAgentIncomeNoDraw(agentInfo.ID, date, sharedMode).Unwrap().(int64) // 分红收益
			//m.TotalMoney = decimal.NewFromInt(m.DrawMoney).Add(decimal.NewFromInt(m.DivindsMoney)).IntPart()
			m.TotalMoney = m.DivindsMoney
			m.OrderCount = dao.NewAgentCountDao().GetSeparateAgentTotalOrderByCreate(agentInfo.ID, date, sharedMode).Unwrap().(int64)    // 生成的订单数
			m.CompleteCount = dao.NewAgentCountDao().GetSeparateAgentTotalOrderCount(agentInfo.ID, 5, date, sharedMode).Unwrap().(int64) // 已完成订单数
			m.CancelCount = dao.NewAgentCountDao().GetSeparateAgentTotalOrderCount(agentInfo.ID, 3, date, sharedMode).Unwrap().(int64)   // 已撤销订单数
			m.PlacesTotal = dao.NewAgentCountDao().GetPlacesTotal(agentInfo.ID).Unwrap().(int64)                                         //获取网点总数
			m.DeviceTotal = dao.NewAgentCountDao().GetDeviceTotal(agentInfo.ID).Unwrap().(int64)                                         //获取设备总数
			m.Name = agentInfo.Name
			m.IncomeDay = date

			count := dao.NewAgentCountDao().CountAgentIncomeInfo(agentInfo.ID, date, sharedMode).Unwrap().(int64)
			if count > 0 { // 更新
				dao.NewAgentCountDao().UpdateAgentIncomeInfo(m)
			} else { // 新增
				dao.NewAgentCountDao().InsertAgentIncomeInfo(m)
			}
		}
	}

	if dayInt > 0 {
		for i := 1; i <= dayInt; i++ {

			date := time.Now().AddDate(0, 0, -i).Format("2006-01-02")
			fmt.Println("修改日期，", date)

			m := agentincome.NewAgentIncomeModel()
			m.AgentUserId = agentInfo.ID
			m.AgentUserName = agentInfo.UserName
			m.Phone = agentInfo.Phone
			m.UserNo = agentInfo.UserNo
			m.SharedMode = sharedMode
			m.TradeTotal = dao.NewAgentCountDao().GetAgentTotalMoney(agentInfo.ID, i, sharedMode).Unwrap().(int64) // 交易 总额
			//m.DrawMoney = dao.NewAgentCountDao().GetAgentTotalMoneyByDraw(lst.ID, d, sharedMode).Unwrap().(int64) // 抽单收益
			//m.DrawCount = dao.NewAgentCountDao().GetAgentTotalDrawCount(lst.ID, d, sharedMode).Unwrap().(int64)   //抽单总金额
			m.DivindsMoney = dao.NewAgentCountDao().GetAgentIncomeNoDraw(agentInfo.ID, i, sharedMode).Unwrap().(int64) // 分红收益
			//m.TotalMoney = decimal.NewFromInt(m.DrawMoney).Add(decimal.NewFromInt(m.DivindsMoney)).IntPart()
			m.TotalMoney = m.DivindsMoney
			m.OrderCount = dao.NewAgentCountDao().GetAgentTotalOrderByCreate(agentInfo.ID, i, sharedMode).Unwrap().(int64)    // 生成的订单数
			m.CompleteCount = dao.NewAgentCountDao().GetAgentTotalOrderCount(agentInfo.ID, i, 5, sharedMode).Unwrap().(int64) // 已完成订单数
			m.CancelCount = dao.NewAgentCountDao().GetAgentTotalOrderCount(agentInfo.ID, i, 3, sharedMode).Unwrap().(int64)   // 已撤销订单数
			m.PlacesTotal = dao.NewAgentCountDao().GetPlacesTotal(agentInfo.ID).Unwrap().(int64)                              //获取网点总数
			m.DeviceTotal = dao.NewAgentCountDao().GetDeviceTotal(agentInfo.ID).Unwrap().(int64)                              //获取设备总数
			m.Name = agentInfo.Name
			m.IncomeDay = date

			count := dao.NewAgentCountDao().CountAgentIncomeInfo(agentInfo.ID, date, sharedMode).Unwrap().(int64)
			if count > 0 { // 更新
				dao.NewAgentCountDao().UpdateAgentIncomeInfo(m)
			} else { // 新增
				dao.NewAgentCountDao().InsertAgentIncomeInfo(m)
			}
		}

	}
}

//更新所有代理商（取消统计网点）
func (task *TaskLogic) AgentIncomeStatisticsCancelPlace(days int, sharedMode string) {
	// 1、获取所有代理商用户

	//agentList := dao.NewUserDao().GetAgentUserListsTest([]int{510, 300003, 300006, 300009, 300010, 300028, 300029, 300034, 300041, 300067, 300076, 300111, 300122, 300143, 300190, 300191, 300202, 300212, 300242, 300302}).Unwrap().([]users.AgentInfo)
	//
	//task.UpdateAgentIncomeStatistics(agentList, days, sharedMode) // 更新商户信息

	//log.Println(agentList)
	agentList := dao.NewUserDao().GetAgentUserLists().Unwrap().([]users.AgentInfo)
	if len(agentList) <= 4 {
		task.UpdateAgentCancelPlaceStatistics(agentList, days, sharedMode)
	} else {
		// 开4个协程
		var wg sync.WaitGroup
		for i := 1; i <= 4; i++ {
			wg.Add(1)
			if i == 4 {
				go func(i int) {
					defer wg.Done()
					task.UpdateAgentCancelPlaceStatistics(agentList[(i-1)*(len(agentList)/4):len(agentList)], days, sharedMode) // 更新商户信息
				}(i)
			} else {
				go func(i int) {
					defer wg.Done()
					task.UpdateAgentCancelPlaceStatistics(agentList[(i-1)*(len(agentList)/4):i*(len(agentList)/4)], days, sharedMode) // 更新商户信息
				}(i)
			}
		}
		wg.Wait()
	}
}

func (task *TaskLogic) UpdateAgentCancelPlaceStatistics(lists []users.AgentInfo, days int, sharedMode string) {
	log.Println(lists)
	for _, lst := range lists {
		if days > 0 {
			for d := 1; d <= days; d++ {
				dateStr := time.Now().AddDate(0, 0, -d).Format("2006-01-02")
				m := agentincome.NewAgentIncomeModel()
				m.AgentUserId = lst.ID
				m.AgentUserName = lst.UserName
				m.Phone = lst.Phone
				m.UserNo = lst.UserNo
				m.SharedMode = sharedMode
				m.TradeTotal = dao.NewAgentCountDao().GetAgentTotalMoney(lst.ID, d, sharedMode).Unwrap().(int64) // 交易 总额
				//m.DrawMoney = dao.NewAgentCountDao().GetAgentTotalMoneyByDraw(lst.ID, d, sharedMode).Unwrap().(int64) // 抽单收益
				//m.DrawCount = dao.NewAgentCountDao().GetAgentTotalDrawCount(lst.ID, d, sharedMode).Unwrap().(int64)   //抽单总金额
				m.DivindsMoney = dao.NewAgentCountDao().GetAgentIncomeNoDraw(lst.ID, d, sharedMode).Unwrap().(int64) // 分红收益
				//m.TotalMoney = decimal.NewFromInt(m.DrawMoney).Add(decimal.NewFromInt(m.DivindsMoney)).IntPart()
				m.TotalMoney = m.DivindsMoney
				m.OrderCount = dao.NewAgentCountDao().GetAgentTotalOrderByCreate(lst.ID, d, sharedMode).Unwrap().(int64)    // 生成的订单数
				m.CompleteCount = dao.NewAgentCountDao().GetAgentTotalOrderCount(lst.ID, d, 5, sharedMode).Unwrap().(int64) // 已完成订单数
				m.CancelCount = dao.NewAgentCountDao().GetAgentTotalOrderCount(lst.ID, d, 3, sharedMode).Unwrap().(int64)   // 已撤销订单数
				//m.PlacesTotal = dao.NewAgentCountDao().GetPlacesTotal(lst.ID).Unwrap().(int64)                              //获取网点总数
				//m.DeviceTotal = dao.NewAgentCountDao().GetDeviceTotal(lst.ID).Unwrap().(int64)                              //获取设备总数
				m.Name = lst.Name
				m.IncomeDay = dateStr

				count := dao.NewAgentCountDao().CountAgentIncomeInfo(lst.ID, dateStr, sharedMode).Unwrap().(int64)
				if count > 0 { // 更新
					dao.NewAgentCountDao().UpdateAgentCancelPlaceInfo(m)
				} else { // 新增
					dao.NewAgentCountDao().InsertAgentIncomeInfo(m)
				}
			}
		}
	}
}

//400775
//400776
//400777
//400778
//400779
//400780
//400781
//400782
//400783
func (task *TaskLogic) MultiplePlaceIncomeStatistics(userId int, days []string, dayInt int, sharedMode string) {
	userIdArr := dao.NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
	placeIdArr := dao.NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)
	if len(days) > 0 {
		for _, d := range days {
			task.SeparateUpdatePlaceIncomeStatistics(d, sharedMode, userIdArr, placeIdArr)
		}
	}
	if dayInt > 0 {
		for i := 1; i <= dayInt; i++ {
			date := time.Now().AddDate(0, 0, -i).Format("2006-01-02")
			task.SeparateUpdatePlaceIncomeStatistics(date, sharedMode, userIdArr, placeIdArr)
		}
	}

}

//-----------网点按天统计
func (task *TaskLogic) SeparatePlaceIncomeStatistics(sharedMode, date string) {
	userIdArr := dao.NewUserDao().GetUserIds().Unwrap().([]int)
	placeIdArr := dao.NewPlaceDao().GetPlaceIds().Unwrap().([]int)
	// 1、获取所有代理商用户

	task.SeparateUpdatePlaceIncomeStatistics(date, sharedMode, userIdArr, placeIdArr)
}

func (task *TaskLogic) SeparateUpdatePlaceIncomeStatistics(date string, sharedMode string, userIdArr, placeIds []int) {

	//查询所有网点，遍历值
	placeList := dao.NewPlaceDao().GetPlaceTestArr(placeIds).Unwrap().([]placemodel.PlaceModel)
	//交易总额
	placeTotalMoneyMap := make(map[string]int64)
	placeTotalMoney := dao.NewAgentCountDao().GetSeparatePlaceTotalMoney(placeIds, date, sharedMode).Unwrap().([]placeincome.SeparatePlaceTotal)

	for _, v := range placeTotalMoney {
		placeTotalMoneyMap[v.Date+"-"+strconv.Itoa(v.PlaceId)] = v.Total
	}

	//查询网点分红收益
	placeDividendsMap := make(map[string]int64)
	placeDividendsList := dao.NewPlaceDao().GetPlaceDividendsByDate(userIdArr, placeIds, date).Unwrap().([]placeresp.PlaceDividendsModel)

	for _, v := range placeDividendsList {
		placeDividendsMap[strconv.Itoa(v.UserId)+"-"+strconv.Itoa(v.PlaceId)] = v.PlaceMoney
	}

	//查询生成的订单数
	placeTotalOrderMap := make(map[string]int64)
	placeTotalOrder := dao.NewAgentCountDao().GetSeparatePlaceTotalOrder(placeIds, date, sharedMode).Unwrap().([]placeincome.SeparatePlaceTotal)

	for _, v := range placeTotalOrder {
		placeTotalOrderMap[v.Date+"-"+strconv.Itoa(v.PlaceId)] = v.Total
	}

	//查询完成订单数
	placeOrderCompleteMap := make(map[string]int64)
	placeOrderComplete := dao.NewAgentCountDao().GetSeparatePlaceTotalOrderComplete(5, placeIds, date, sharedMode).Unwrap().([]placeincome.SeparatePlaceTotal)

	for _, v := range placeOrderComplete {
		placeOrderCompleteMap[v.Date+"-"+strconv.Itoa(v.PlaceId)] = v.Total
	}

	//撤销订单数
	placeOrderCancelMap := make(map[string]int64)
	placeOrderCancel := dao.NewAgentCountDao().GetSeparatePlaceTotalOrderComplete(3, placeIds, date, sharedMode).Unwrap().([]placeincome.SeparatePlaceTotal)
	for _, v := range placeOrderCancel {
		placeOrderCancelMap[v.Date+"-"+strconv.Itoa(v.PlaceId)] = v.Total
	}

	//设备总数
	deviceCountMap := make(map[int]int64)
	deviceCountModel := dao.NewDeviceDao().GetDeviceCountByPlaceIdArr(placeIds).Unwrap().([]placeresp.DeviceCountPlaceIdsModel)
	//设备总数封装map
	for _, v := range deviceCountModel {
		deviceCountMap[v.PlaceId] = v.DeviceTotal
	}

	//是否查询过
	countPlaceIncomeInfoMap := make(map[string]int64)
	countPlaceIncomeInfo := dao.NewAgentCountDao().SeparateCountPlaceIncomeInfo(placeIds, date, sharedMode).Unwrap().([]placeincome.SeparatePlaceTotal)
	//设备总数封装map
	for _, v := range countPlaceIncomeInfo {
		countPlaceIncomeInfoMap[v.Date+"-"+strconv.Itoa(v.PlaceId)] = v.Total
	}

	// 查询首单时间
	placeFirstOrderTimeMap := make(map[int]string)
	placeFirstOrderTimeList := dao.NewPlaceDao().GetPlaceFirstOrderTime(placeIds).Unwrap().([]placeresp.PlaceFirstOrderTime)

	for _, v := range placeFirstOrderTimeList {
		placeFirstOrderTimeMap[v.PlaceId] = v.FirsDate
	}

	//扫码用户
	scanCodeUserMap := make(map[string]int64)
	scanCodeUserList := dao.NewUserDao().GetScanCodeUser(placeIds, date).Unwrap().([]users.ScanCodeUser)
	for _, v := range scanCodeUserList {
		scanCodeUserMap[v.Date+"-"+strconv.Itoa(v.PlaceId)] = v.TotalUser
	}

	loc, _ := time.LoadLocation("Local")
	var updateCount, insertCount int
	for _, lst := range placeList {
		//createTime := time.Unix(int64(lst.CreateAt),64).Format("2006-01-02")
		dateUnix, _ := time.ParseInLocation("2006-01-02", date, loc)

		//fmt.Println("创建时间", int64(lst.CreateAt), "统计时间", dateUnix.Unix())
		if int64(lst.CreateAt) >= dateUnix.Unix() {
			continue
		}

		//查询该用户下的所有网点
		//placesIdArr := dao.NewUserDao().GetPlacesId(lst.ID).Unwrap().([]int)

		dateStr := date
		//d := time.Now().AddDate(0, 0, -d).Unix()
		m := &placeincome.PlaceIncomeModel{}
		m.PlaceId = lst.Id             //网点ID
		m.PlaceName = lst.PlaceName    //网点名称
		m.PlaceCreateAt = lst.CreateAt //创建时间
		m.IncomeDay = dateStr          //天数
		m.SharedMode = sharedMode
		m.AgentUserId = lst.UserID

		//m.SettlementMoney = dao.NewAgentCountDao().GetSeparatePlaceTotalMoneyByDraw(lst.Id, date, sharedMode).Unwrap().(int64) // 交易 总额
		// 交易总额(结算时间)
		if v, ok := placeTotalMoneyMap[date+"-"+strconv.Itoa(lst.Id)]; ok {
			m.SettlementMoney = v
		} else {
			m.SettlementMoney = 0
		}
		//m.Income = dao.NewAgentCountDao().GetSeparateAPlaceIncomeNoDraw(lst.Id, lst.UserID, date, sharedMode).Unwrap().(int64) // 分红收益

		//当前商户收益
		if v, ok := placeDividendsMap[strconv.Itoa(lst.UserID)+"-"+strconv.Itoa(lst.Id)]; ok {
			m.Income = v
		} else {
			m.Income = 0
		}

		//m.OrderCount = dao.NewAgentCountDao().GetSeparatePlaceTotalOrderByCreate(lst.Id, date, sharedMode).Unwrap().(int64) // 生成的订单数
		// 生成的订单数
		if v, ok := placeTotalOrderMap[date+"-"+strconv.Itoa(lst.Id)]; ok {
			m.OrderCount = v
		} else {
			m.OrderCount = 0
		}

		//m.CompleteCount = dao.NewAgentCountDao().GetSeparatePlaceTotalOrderCount(lst.Id, 5, date, sharedMode).Unwrap().(int64) // 已完成订单数
		// 已完成订单数
		if v, ok := placeOrderCompleteMap[date+"-"+strconv.Itoa(lst.Id)]; ok {
			m.CompleteCount = v
		} else {
			m.CompleteCount = 0
		}

		//m.CancelCount = dao.NewAgentCountDao().GetSeparatePlaceTotalOrderCount(lst.Id, 3, date, sharedMode).Unwrap().(int64) // 已撤销订单数
		//已撤销订单数
		if v, ok := placeOrderCancelMap[date+"-"+strconv.Itoa(lst.Id)]; ok {
			m.CancelCount = v
		} else {
			m.CancelCount = 0
		}

		//m.DeviceTotal = dao.NewAgentCountDao().GetPlaceDeviceTotal(lst.Id).Unwrap().(int64) //获取设备总数

		//网点设备
		if v, ok := deviceCountMap[lst.Id]; ok {
			m.DeviceTotal = v
		} else {
			m.DeviceTotal = 0
		}

		m.HotelId = lst.HotelId
		var count int64
		//count := dao.NewAgentCountDao().CountPlaceIncomeInfo(lst.Id, dateStr, sharedMode).Unwrap().(int64)
		if v, ok := countPlaceIncomeInfoMap[date+"-"+strconv.Itoa(lst.Id)]; ok {
			count = v
		} else {
			count = 0
		}

		//查询首单时间
		if v, ok := placeFirstOrderTimeMap[lst.Id]; ok {
			m.FirstOrderDate = v
		} else {
			m.FirstOrderDate = ""
		}
		//扫码用户
		if v, ok := scanCodeUserMap[date+"-"+strconv.Itoa(lst.Id)]; ok {
			m.ScanCodeUser = v
		} else {
			m.ScanCodeUser = 0
		}

		if count > 0 { // 更新
			updateCount++
			fmt.Println("进来更新了", updateCount, dateStr)
			dao.NewAgentCountDao().UpdatePlaceIncomeInfo(m)
		} else { // 新增
			insertCount++
			fmt.Println("进来新增了", insertCount, dateStr)
			dao.NewAgentCountDao().InsertPlaceIncomeInfo(m)
		}
	}
}

func (task *TaskLogic) TaskLogicPlaceIncomeStatistics(days int, sharedMode string) {
	task.UpdatePlaceIncomeStatisticsAll(days, sharedMode)
}

// 同步网点激活状态
func (task *TaskLogic) SyncPlaceActiveStatus() {
	sql := `UPDATE places p LEFT JOIN orders o ON p.id = o.place_id SET active_status=1 WHERE p.active_status=0 AND o.id IS NOT NULL`
	if db := global.Orm.Exec(sql); db.Error != nil {
		logs.Error("SyncPlaceActiveStatus", db.Error)
	}
}

// 同步物流状态
func (task *TaskLogic) SyncLogisticsStatus() {
	list := dao.NewLogisticsDao().GetLogisticsStatusList().
		Unwrap().([]*placemodel.PlaceLogisticsModel)

	for _, item := range list {
		if utf8.RuneCountInString(item.LogisticsOrderNo) > 6 {
			if info := dao.NewLogisticsDao().GetPlaceLogisticsInfoNotSelectDb(item).Unwrap().(dao.ThirdLogisticsInfo); info.Code == 200 {
				logs.Info("同步物流状态成功：" + item.LogisticsOrderNo)
			} else {
				logs.Error("同步物流状态失败：" + item.LogisticsOrderNo)
			}
			time.Sleep(time.Second)
		}
	}
}

func (task *TaskLogic) HandelSyncOrders() {

	var tradeNo []string
	global.Orm.Table("orders").
		Select("trade_no").
		Where("state = 2 and DATE_FORMAT( FROM_UNIXTIME( create_at ), '%Y-%m-%d' ) <= date_sub(curdate(), interval 3 day)").
		Find(&tradeNo)
	// 查询微信订单信息
	wc := NewSettingLogic().GetPaySetting()
	var b bool
	for _, v := range tradeNo {
		resultData, err := wechatpay.ApiQueryPayScoreOrder(v, wc) // 查询微信订单
		if err != nil {
			log.Println("查询订单出错,订单号：", v)
			continue
		}

		if v != "" { // 有订单更新
			// 更新微信订单状态
			// 1:等待下单 2:使用中 3:已撤销 4:交易失败 5:已完成 6:支付超时 7:待守约 10:已删除 11: 转入退款
			var status int8
			var stateDesc, stateDoning string
			switch resultData.Get("state") {
			case "CREATED":
				status = 1 // CREATED 商户已创建服务订单
				stateDesc = "商户已创建服务订单"
			case "DOING":
				status = 2 // DOING 服务订单进行中
				stateDesc = "服务订单进行中"
			case "DONE":
				status = 5 // DONE 服务订单完成
				stateDesc = "服务订单完成"
			case "REVOKED":
				status = 3 // REVOKED 商户取消服务订单
				stateDesc = "商户取消服务订单"
			case "EXPIRED":
				status = 4 // EXPIRED 服务订单已失效
				stateDesc = "服务订单已失效"
			}
			if resultData.Get("state") == "DONE" {
				stateDoning = "COMPLETE"
			} else {
				stateDoning = resultData.Get("state_description")
			}

			// 结算金额大于0时才会返回 结算通知更新订单信息
			if resultData.Get("collection") != "" {
				apiData := wechatpay.NewPayData()
				_ = apiData.FromJsonStr(resultData.Get("collection"))
				state := apiData.Get("state")                                           // 状态 USER_PAYING：待支付 USER_PAID：已支付
				totalAmount, _ := strconv.ParseInt(apiData.Get("total_amount"), 10, 64) // 总金额
				//paying_amount := apiData.Get("paying_amount") // 待支付金额
				paidAmount, _ := strconv.ParseInt(apiData.Get("paid_amount"), 10, 64) // 已支付金额
				log.Println(state, totalAmount, paidAmount)                           // USER_PAID 100 0 100

				//log.Println(apiData.Get("details"))
				//var details []detailData
				var details []map[string]interface{}
				_ = json.Unmarshal([]byte(apiData.Get("details")), &details)
				var transactionId string
				if len(details) > 0 {
					transactionId = details[0]["transaction_id"].(string)
				}
				log.Println("打印测试订单详情", details)

				var s int8
				if state == "USER_PAYING" { // 待支付 --- 待守约
					s = 7
					m := orders.New()
					m.State = s
					m.Money = totalAmount
					m.MoneyStr = decimal.NewFromInt(totalAmount).Div(decimal.NewFromInt(100)).StringFixed(2)

					m.PayMoney = paidAmount
					m.PayMoneyStr = decimal.NewFromInt(paidAmount).Div(decimal.NewFromInt(100)).StringFixed(2)

					//m.PayAt = dingo.Time(wechatpay.ConvIntTime(fmt.Sprintf("%v", details[0]["paid_time"])))
					//m.SettlementState = 3
					//amount, _ := strconv.ParseInt(fmt.Sprintf("%v", details[0]["amount"]), 10, 64)
					//m.SettlementMoney = amount
					//m.SettlementMoneyStr = decimal.NewFromInt(amount).Div(decimal.NewFromInt(100)).StringFixed(2)
					m.TradeStateDesc = stateDesc
					m.TradeStateDoing = stateDoning
					m.TradeState = resultData.Get("state")
					m.TradeNo = resultData.Get("out_order_no")
					m.Openid = resultData.Get("openid")

					m.EndAt = dingo.Time(time.Now().Unix())
					m.OutTradeNo = transactionId

					b = dao.NewOrderDao().UpdateOrderByTradeNo(m).Unwrap().(bool)
					if !b {
						log.Println("修改订单状态失败，订单号：", v, b)
					}
				} else {
					s = status
					m := orders.New()
					m.State = s
					m.Money = totalAmount
					m.MoneyStr = decimal.NewFromInt(totalAmount).Div(decimal.NewFromInt(100)).StringFixed(2)

					m.PayMoney = paidAmount
					m.PayMoneyStr = decimal.NewFromInt(paidAmount).Div(decimal.NewFromInt(100)).StringFixed(2)

					m.PayAt = dingo.Time(wechatpay.ConvIntTime(fmt.Sprintf("%v", details[0]["paid_time"])))
					m.SettlementState = 3
					amount, _ := strconv.ParseInt(fmt.Sprintf("%v", details[0]["amount"]), 10, 64)
					m.SettlementMoney = amount
					m.SettlementMoneyStr = decimal.NewFromInt(amount).Div(decimal.NewFromInt(100)).StringFixed(2)
					m.TradeStateDesc = stateDesc
					m.TradeStateDoing = stateDoning
					m.TradeState = resultData.Get("state")
					m.TradeNo = resultData.Get("out_order_no")
					m.Openid = resultData.Get("openid")

					m.EndAt = dingo.Time(time.Now().Unix())
					m.OutTradeNo = transactionId

					b = dao.NewOrderDao().UpdateOrderByTradeNo(m).Unwrap().(bool)
					if !b {
						log.Println("修改订单状态失败，订单号：", v, b)
					}
				}

			} else { // 订单金额为0时
				m := orders.New()
				m.State = status
				m.TradeStateDesc = stateDesc
				m.TradeStateDoing = stateDoning
				m.TradeState = resultData.Get("state")
				m.TradeNo = resultData.Get("out_order_no")
				m.Openid = resultData.Get("openid")
				m.EndAt = dingo.Time(time.Now().Unix())
				b = dao.NewOrderDao().UpdateOrderByTradeNo(m).Unwrap().(bool)
				if !b {
					log.Println("修改订单状态失败，订单号：", v, b)
				}
			}
		} else { // 新增
			memInfo := memberdao.NewMemberDao().GetMemberInfoByOpenid(resultData.Get("openid")).Unwrap().(*membermodel.MembersModel)
			devInfo := dao.NewDeviceDao().FetchDeviceInfoWithType(resultData.Get("attach")).Unwrap().(*devices.DeviceType)
			//ployInfo := dao.NewPloysDao().GetPlacePloyInfo(devInfo.PlaceId, devInfo.SharedMode).Unwrap().(*ploys.PloyModel) // 获取商户最新奖励规则配置

			var priceList []prices.PriceModel
			if devInfo.FeeMode == 1 { // 计时
				priceList = dao.NewPricesDao().GetPlacePriceByTypeId(devInfo.PlaceId, devInfo.DeviceTypeId, 1, 1, "create_at desc").Unwrap().([]prices.PriceModel)
			} else { // 套餐
				priceList = dao.NewPricesDao().GetPlacePriceByTypeId(devInfo.PlaceId, devInfo.DeviceTypeId, 1, 1, "pay_money asc").Unwrap().([]prices.PriceModel)
			}

			userInfo := dao.NewUserDao().GetUserInfoByPlaceId(devInfo.PlaceId).Unwrap().(*users.UserModel)
			uInfo := dao.GetParentUserInfoById(userInfo)

			isDraw := 0 // 不抽单

			timeRange := &struct {
				StartTime string `json:"start_time"`
				EndTime   string `json:"end_time"`
			}{}
			_ = json.Unmarshal([]byte(resultData.Get("time_range")), timeRange)
			stamp := wechatpay.ConvIntTime(timeRange.StartTime)
			//stamp, _ := time.ParseInLocation("20060102150405", timeRange.StartTime, time.Local)
			money, _ := strconv.ParseInt(resultData.Get("total_amount"), 10, 64)

			// 1:等待下单 2:使用中 3:已撤销 4:交易失败 5:已完成 6:支付超时 7:待守约 10:已删除 11: 转入退款
			var status int8
			var stateDesc string
			switch resultData.Get("state") {
			case "CREATED":
				status = 1 // CREATED 商户已创建服务订单
				stateDesc = "商户已创建服务订单"
			case "DOING":
				status = 2 // DOING 服务订单进行中
				stateDesc = "服务订单进行中"
			case "DONE":
				status = 5 // DONE 服务订单完成
				stateDesc = "服务订单完成"
			case "REVOKED":
				status = 3 // REVOKED 商户取消服务订单
				stateDesc = "商户取消服务订单"
			case "EXPIRED":
				status = 4 // EXPIRED 服务订单已失效
				stateDesc = "服务订单已失效"
			}

			// 不存在  新增
			m := orders.New().Mutate(
				orders.WithAppid(resultData.Get("appid")),
				orders.WithDeviceSn(resultData.Get("attach")),
				orders.WithMchid(resultData.Get("mchid")),
				orders.WithOpenid(resultData.Get("openid")),
				orders.WithOutTradeNo(resultData.Get("order_id")),  // 微信订单号
				orders.WithTradeNo(resultData.Get("out_order_no")), // 商户订单号
				//orders.WithPayAt(dingo.Time(stamp.Unix())),                        // 支付时间
				orders.WithPayAt(dingo.Time(stamp)), // 支付时间
				//orders.WithTradeType(resultData.Get("trade_type")),                    // 订单支付类型 - 微信支付分支付
				orders.WithTradeType("PreAuthPay"), // 订单支付类型 - 微信支付分支付
				orders.WithMoney(money),
				orders.WithMoneyStr(decimal.NewFromInt(money).Div(decimal.NewFromInt(100)).StringFixed(2)),
				orders.WithTradeState(resultData.Get("state")), // 微信交易 状态
				orders.WithTradeStateDesc(stateDesc),           // 微信交易状态描述
				orders.WithTradeStateDoing(resultData.Get("state_description")),
				orders.WithCreateAt(dingo.Time(time.Now().Unix())),
				orders.WithState(status),
				orders.WithOrderFrom("weixin"),
				orders.WithPayFrom(1), // 1免押 2押金
				orders.WithMemberId(memInfo.UUID),
				orders.WithMemberName(memInfo.NickName),
				orders.WithPlaceId(devInfo.PlaceId),
				orders.WithPlaceName(devInfo.PlaceName),
				orders.WithSharedMode(devInfo.SharedMode),
				orders.WithPayMoney(money),
				orders.WithPayMoneyStr(decimal.NewFromInt(money).Div(decimal.NewFromInt(100)).StringFixed(2)),
				orders.WithTitle(devInfo.DeviceName),
				orders.WithFeeMode(int8(devInfo.FeeMode)),
				orders.WithPayType(3),
				orders.WithProductId(priceList[0].ProductId),
				orders.WithIsDraw(int8(isDraw)), // 1抽单 0不抽单
				orders.WithIsTianHai(0),         // 0新系统  1天海
				orders.WithUserId(userInfo.ID),
				orders.WithUserName(userInfo.Name),
				orders.WithParentId(userInfo.ParentID),
				orders.WithAgentUserId(uInfo.ID),
				orders.WithSettlementWay(1), // 未结算
				orders.WithProdType(devInfo.ProdType), // 设备类型  1  2  3
			)
			b = dao.NewOrderDao().InsertOrder(m).Unwrap().(bool)
			if !b {
				log.Println("修改订单状态失败，订单号：", v, b)
			}
		}

	}

}

// 小程序订阅消息推送

// 同步网点的设备数
func (task *TaskLogic) SyncPlaceDeviceCount() {
	//获取网点设备总数
	list := dao.NewPlaceDao().GetPlaceDeviceCount().Unwrap().([]placeresp.DeviceCountPlaceIdsModel)
	for _, lst := range list {
		dao.NewPlaceDao().UpdatePlaceCount(lst.PlaceId, lst.DeviceTotal)
	}
}

//用户的下级门店添加新套餐规则
func (task *TaskLogic) PlacesInsertPrices(userId int) {

	//查询门店
	placesBranchIds := dao.NewUserDao().GetPlacesId(userId).Unwrap().([]int)
	//userIds := dao.NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
	//获取直属或下级网点Id
	userIdArr := dao.NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
	placeIdArr := dao.NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)

	//合并网点
	placesBranchIds = append(placesBranchIds, placeIdArr...)

	//去重网点
	placesIds := utils.RemoveRepByMap(placesBranchIds)

	var payMoney int64
	var useDuration int
	var setMealNum int8
	var ruleName string
	//遍历门店
	for _, id := range placesIds {

		for i := 1; i <= 4; i++ {

			switch i {
			case 1:
				payMoney = 300
				useDuration = 120
				setMealNum = 2
				ruleName = "3元，使用2小时"
			case 2:
				payMoney = 500
				useDuration = 180
				setMealNum = 3
				ruleName = "5元，使用3小时"
			case 3:
				payMoney = 800
				useDuration = 600
				setMealNum = 4
				ruleName = "8元，使用10小时"
			case 4:
				payMoney = 1200
				useDuration = 1440
				setMealNum = 5
				ruleName = "12元，使用24小时"

			}

			//添加
			m := prices.New()
			m.DeviceTypeId = 12
			m.PlaceId = id
			m.Status = 1
			m.ProductId = utils.Str2Md5(helper.GenerateUUID())
			m.UseDuration = useDuration // 使用时长
			m.PayMoney = payMoney       // 支付金额-单位分
			m.SetMealNum = setMealNum   // 规则序号
			m.RuleName = ruleName       // 规则名
			m.IsRecommend = 2           // 是否推荐
			m.Priority = 10             // 排序
			m.CreateAt = dingo.Time(time.Now().Unix())
			dao.NewPricesDao().InsertPlacePrice(m).Unwrap() // 新增 商户价格
		}

	}

}

func (task *TaskLogic) PlacesInsertPricesByplaceId(placeIds []string) {
	var payMoney int64
	var useDuration int
	var setMealNum, status int8
	var ruleName string
	//遍历门店
	for _, idStr := range placeIds {
		id, _ := strconv.Atoi(idStr)
		for i := 1; i <= 5; i++ {
			switch i {
			case 1:
				payMoney = 100
				useDuration = 20
				setMealNum = 1
				ruleName = "1元，使用20分钟"
				status = 2
			case 2:
				payMoney = 300
				useDuration = 120
				setMealNum = 2
				ruleName = "3元，使用2小时"
				status = 1
			case 3:
				payMoney = 500
				useDuration = 180
				setMealNum = 3
				ruleName = "5元，使用3小时"
				status = 1
			case 4:
				payMoney = 800
				useDuration = 600
				setMealNum = 4
				ruleName = "8元，使用10小时"
				status = 1
			case 5:
				payMoney = 1200
				useDuration = 1440
				setMealNum = 5
				ruleName = "12元，使用24小时"
				status = 1
			}
			//添加
			m := prices.New()
			m.DeviceTypeId = 12
			m.PlaceId = id
			m.Status = status
			m.ProductId = utils.Str2Md5(helper.GenerateUUID())
			m.UseDuration = useDuration // 使用时长
			m.PayMoney = payMoney       // 支付金额-单位分
			m.SetMealNum = setMealNum   // 规则序号
			m.RuleName = ruleName       // 规则名
			m.IsRecommend = 2           // 是否推荐
			m.Priority = 10             // 排序
			m.CreateAt = dingo.Time(time.Now().Unix())
			dao.NewPricesDao().InsertPlacePrice(m).Unwrap() // 新增 商户价格
		}

	}

}

// 计时价格 批量修改
func (task *TaskLogic) PlacesInsertPricesToJishi(userId int) {
	var placeIds []int
	//查询门店
	//placesBranchIds := dao.NewUserDao().GetPlacesId(userId).Unwrap().([]int) // 查询 分公司下所有门店
	//userIds := dao.NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
	//获取直属或下级网点Id
	userIdArr := dao.NewUserDao().QueryChildUserIds(userId).Unwrap().([]int)
	placeIdArr := dao.NewPlaceDao().GetPlaceByIds(userIdArr).Unwrap().([]int)

	//合并网点
	placeIds = append(placeIds, placeIdArr...)

	//去重网点
	placesIds := utils.RemoveRepByMap(placeIds)

	for _, id := range placesIds {
		//添加
		m := prices.New()
		m.DeviceTypeId = 10
		m.PlaceId = id
		m.Status = 1
		m.ProductId = utils.Str2Md5(helper.GenerateUUID())

		m.MaxPayPrice = 1200     // 日封顶价格
		m.PayIntervalPrice = 200 // 每60分钟支付2元
		m.PayInterval = 60       // 每60分钟支付2元
		m.MaxTime = 1440         // 最大使用时长
		m.BasePrice = 200        // 最低使用价格
		m.BaseTimes = 60         // 最低使用时长
		m.FreeTimes = 0          // 免费使用时长
		m.Deposit = 1200         //  押金

		m.CreateAt = dingo.Time(time.Now().Unix())
		dao.NewPricesDao().InsertPlacePrice(m).Unwrap() // 新增 商户价格
	}

}

func (task *TaskLogic) PlacesInsertPricesToJishiByPlaceId(placeIds []string) {
	for _, idStr := range placeIds {
		id, _ := strconv.Atoi(idStr)
		//添加
		m := prices.New()
		m.DeviceTypeId = 10
		m.PlaceId = id
		m.Status = 1
		m.ProductId = utils.Str2Md5(helper.GenerateUUID())

		m.MaxPayPrice = 1200     // 日封顶价格
		m.PayIntervalPrice = 200 // 每60分钟支付2元
		m.PayInterval = 60       // 每60分钟支付2元
		m.MaxTime = 1440         // 最大使用时长
		m.BasePrice = 200        // 最低使用价格
		m.BaseTimes = 60         // 最低使用时长
		m.FreeTimes = 0          // 免费使用时长
		m.Deposit = 1200         //  押金

		m.CreateAt = dingo.Time(time.Now().Unix())
		dao.NewPricesDao().InsertPlacePrice(m).Unwrap() // 新增 商户价格
	}

}

// ------------------- 定时查看使用时长已到期的用户 -----------------------//

func (task *TaskLogic) AliPayAutoCompleteMemberOrder() {

	// 查询订单中正在使用的订单
	var lists []orders.OrderModel
	global.Orm.Table("orders").
		Where("state = ?", 2).
		Where("order_from = ?", "zhifubao").Find(&lists)

	// 遍历正在使用中的订单 - 如果订单的使用时长已超过，则自动扣款
	for _, lst := range lists {
		//log.Println(lst.TradeNo)
		param := &request.CloseOrderReq{}
		param.DeviceSn = lst.DeviceSn
		param.TradeNo = lst.TradeNo
		param.EndTime = time.Now().Unix()
		param.ProductId = lst.ProductId
		param.Openid = lst.Openid

		if lst.Openid == "" {
			m := membermodel.New()
			global.Orm.Table("members").Where("uuid = ?", lst.MemberId).Find(m).Limit(1)
			param.Openid = m.XcxOpenid
		}
		// 判断使用时长是否超时
		useTime := param.EndTime - int64(lst.PayAt)
		ruleInfo := dao.NewPricesDao().GetPriceDetail(lst.ProductId).Unwrap().(*prices.PriceModel)

		if lst.FeeMode == 1 { // 计时
			if useTime/60 >= int64(ruleInfo.MaxTime) {
				NewOrderLogic().HandleZfbEndOrder(param)
			}
		} else {
			if useTime/60 >= int64(ruleInfo.UseDuration) {
				NewOrderLogic().HandleZfbEndOrder(param)
			}
		}

	}

	// 预授权支付（支付分支付），自动扣款失败则为  待守约
	// 押金支付暂时不需要
}

//告警
func SyncAlarm() {
	//查询提现大于两千元的用户
	cashUserList := dao.NewCashDao().GetCashUser().Unwrap().([]*cashlog.UserWithdrawalLog)
	if len(cashUserList) > 0 {

	}

	sw := sync.WaitGroup{}
	sw.Add(3)
	var placesSevenDayOrder []*placeresp.PlaceRankList
	var placesFifteenDayOrder []*placeresp.PlaceRankList
	var placesThirtyDayOrder []*placeresp.PlaceRankList
	go func() {
		//查询门店订单 7天
		placesSevenDayOrder = dao.NewPlaceDao().GetPlaceRecentlyOrder("7").Unwrap().([]*placeresp.PlaceRankList)
		if len(placesSevenDayOrder) > 0 {

		}
		sw.Done()
	}()
	go func() {

		//查询门店订单 15天
		placesFifteenDayOrder = dao.NewPlaceDao().GetPlaceRecentlyOrder("15").Unwrap().([]*placeresp.PlaceRankList)
		if len(placesFifteenDayOrder) > 0 {

		}
		sw.Done()
	}()
	go func() {
		//查询门店订单 30天
		placesThirtyDayOrder = dao.NewPlaceDao().GetPlaceRecentlyOrder("30").Unwrap().([]*placeresp.PlaceRankList)
		if len(placesThirtyDayOrder) > 0 {

		}
		sw.Done()
	}()

	sw.Wait()

}

//运营内部统计
func (task *TaskLogic) InternalStatistics() {
	var err error
	var userIds []int

	//查询用户信息
	data := dao.NewStatisticalDao().GetStatisticsUserList().Unwrap().([]*internalstatistics.InternalStatistics)
	for _, v := range data {
		userIds = append(userIds, v.UserId)
	}

	sw := sync.WaitGroup{}
	sw.Add(4)
	userIds = utils.ToIntRepetition(userIds)
	var settlementMoney []*internalstatistics.InternalStatistics
	var placeAndDeviceTotal []*internalstatistics.InternalStatistics
	var placeNotEarnings []*internalstatistics.InternalStatistics
	var deviceNotEarnings []*internalstatistics.InternalStatistics

	settlementMoneyMap := map[int]int64{}
	placeNotEarningsMap := map[int]int64{}
	deviceNotEarningsMap := map[int]int64{}
	placeAndDeviceTotalMap := make(map[int]*internalstatistics.InternalStatistics, 0)

	go func() {
		//查询流水
		settlementMoney, err = dao.NewStatisticalDao().StatisticsMoneyList(userIds)
		for _, v := range settlementMoney {
			settlementMoneyMap[v.UserId] = v.Money
		}

		sw.Done()
	}()
	go func() {
		//查询网点数和设备数
		placeAndDeviceTotal, err = dao.NewStatisticalDao().StatisticsPlaceAndDeviceTotal(userIds)
		for _, v := range placeAndDeviceTotal {
			placeAndDeviceTotalMap[v.UserId] = v
		}

		sw.Done()
	}()
	go func() {
		//查询没有产生订单的网点
		placeNotEarnings, err = dao.NewStatisticalDao().StatisticsPlacesNotEarnings(userIds)
		for _, v := range placeNotEarnings {
			placeNotEarningsMap[v.UserId] = v.NotIncomePlace
		}

		sw.Done()
	}()
	//
	go func() {
		//查询没有产生订单的设备
		deviceNotEarnings, err = dao.NewStatisticalDao().StatisticsDeviceNotEarnings(userIds)
		for _, v := range deviceNotEarnings {
			deviceNotEarningsMap[v.UserId] = v.NotIncomeDevice
		}
		sw.Done()
	}()
	sw.Wait()
	//
	for _, m := range data {

		if v, ok := settlementMoneyMap[m.UserId]; ok {
			m.Money = v
		}

		if v, ok := placeAndDeviceTotalMap[m.UserId]; ok {
			m.DeviceTotal = v.DeviceTotal
			m.PlaceTotal = v.PlaceTotal
		}

		if v, ok := placeNotEarningsMap[m.UserId]; ok {
			m.NotIncomePlace = v
		}

		if v, ok := deviceNotEarningsMap[m.UserId]; ok {
			m.NotIncomeDevice = v
		}
		createAt := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
		m.CreateAt = createAt
		if m.PlaceTotal > 0 && m.NotIncomePlace == 0 {
			m.NotIncomePlaceProbability = "100"
		} else if m.PlaceTotal == 0 {
			m.NotIncomePlaceProbability = "0"
		} else {
			m.NotIncomePlaceProbability = decimal.NewFromInt(m.PlaceTotal).Div(decimal.NewFromInt(m.NotIncomePlace)).StringFixed(2)
		}
		if m.Money > 0 {
			m.DeviceProbability = decimal.NewFromInt(m.Money).Div(decimal.NewFromInt(m.DeviceTotal)).StringFixed(2)
		}

		count := dao.NewStatisticalDao().InternalIsStatistics(m.UserId, createAt).Unwrap().(int64)
		if count > 0 { // 更新
			dao.NewStatisticalDao().UpdateInternalStatistics(m)
		} else { // 新增
			dao.NewStatisticalDao().InsertInternalStatistics(m)
		}
	}
}

// 解绑异常设备
func (task *TaskLogic) SyncUnbindAbnormalDevices() {
	global.Orm.Table("devices").Where("state=2 AND place_id=0").Update("state", 1)
}
